<template>
  <div>
    <!-- 添加或修改项目验收对话框 -->
    <el-drawer
      ref="drawer"
      :title="title"
      direction="rtl"
      :visible.sync="open"
      size="80%"
      append-to-body
      :wrapperClosable="false"
    >
      <el-card
        class="box-card"
        style="width: 96%; margin-left: 20px; min-height: 90vh"
      >
        <el-row>
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="所属部门" prop="deptId">
                  <treeselect
                    v-model="form.deptId"
                    :options="deptOptions"
                    :show-count="true"
                    placeholder="请选择归属部门"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目编号" prop="projectOn">
                  <el-input
                    v-model="form.projectOn"
                    placeholder="请输入项目编号"
                    readonly
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="商机名称" prop="projectName">
                  <el-input
                    v-model="form.projectName"
                    placeholder="请输入商机名称"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户名称" prop="customerId">
                  <el-select
                    v-model="form.customerId"
                    placeholder="请选择客户名称"
                    style="width: 100%"
                    disabled
                    filterable
                  >
                    <el-option
                      v-for="customer in customerList"
                      :key="customer.customerId"
                      :label="customer.customerName"
                      :value="customer.customerId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="开始日期" prop="startTime">
                  <el-date-picker
                    clearable
                    style="width: 100%"
                    v-model="form.startTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择开始日期"
                    disabled
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束日期" prop="endTime">
                  <el-date-picker
                    clearable
                    style="width: 100%"
                    v-model="form.endTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择结束日期"
                    disabled
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="申请人" prop="applyUser">
                  <el-select
                    v-model="form.applyUser"
                    placeholder="请选择申请人"
                    style="width: 100%"
                    filterable
                    clearable
                    disabled
                  >
                    <el-option
                      v-for="user in userList"
                      :key="user.userId"
                      :label="user.userName"
                      :value="user.userId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="负责人" prop="principalId">
                  <el-select
                    v-model="form.principalId"
                    placeholder="请选择负责人"
                    style="width: 100%"
                    filterable
                    clearable
                    multiple
                    disabled
                  >
                    <el-option
                      v-for="user in userList"
                      :key="user.userId"
                      :label="user.userName"
                      :value="user.userId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="回款情况" prop="payment">
                  <el-input
                    v-model="form.payment"
                    placeholder="请输入回款情况说明"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="项目金额" prop="projectSum">
                  <el-input
                    v-model="form.projectSum"
                    placeholder="请输入项目金额"
                    disabled
                  >
                    <template slot="append">{{
                      digitUppercase(form.projectSum)
                    }}</template></el-input
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="最终利润" prop="profit">
                  <el-input
                    v-model="form.profit"
                    placeholder="请输入最终利润"
                    readonly
                  >
                    <template slot="append">{{
                      digitUppercase(form.profit)
                    }}</template></el-input
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="利润率" prop="profitMargin">
                  <el-input
                    v-model="form.profitMargin"
                    placeholder="请输入利润率"
                    readonly
                  >
                    <template slot="append">%</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-divider>项目成本费用支出</el-divider>
                <div class="box-form">
                  <el-card
                    class="box-card"
                    shadow="never"
                    v-for="(details, index) in form.detailsList"
                    :key="index"
                  >
                    <el-row>
                      <el-col :span="20">
                        <el-form-item label="是否存在明细" prop="isRequired">
                          <el-checkbox
                            v-model="details.isRequired"
                            true-label="1"
                            false-label="0"
                            disabled
                            >无</el-checkbox
                          >
                        </el-form-item>
                      </el-col>
                      <el-col :span="details.itemWidth">
                        <el-form-item label="费用类型" prop="detailsName">
                          <el-select
                            v-model="details.detailsType"
                            placeholder="请选择费用类型"
                            style="width: 100%"
                            disabled
                            @change="detailsTypeChange(details)"
                          >
                            <el-option
                              v-for="dict in dict.type.crm_fee_type"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="details.itemWidth">
                        <el-form-item label="费用名称" prop="detailsName">
                          <el-input
                            :readonly="details.flag === '1'"
                            v-model="details.detailsName"
                            placeholder="请输入费用名称"
                            disabled
                          />
                        </el-form-item>
                      </el-col>
                      <el-col
                        :span="8"
                        v-if="
                          details.detailsType === '1' ||
                          details.detailsType === '4'
                        "
                      >
                        <el-form-item label="费用来源" prop="url">
                          <el-select
                            v-model="details.applyIds"
                            multiple
                            filterable
                            placeholder="请选择费用来源"
                            style="width: 100%"
                            disabled
                            @change="setterApplyAmount($event, details)"
                          >
                            <el-option
                              v-for="apply in applyList"
                              :key="apply.applyId"
                              :label="apply.applyName"
                              :value="apply.applyId"
                            >
                              <span style="float: left">{{
                                apply.applyName
                              }}</span>
                              <span
                                style="
                                  float: right;
                                  color: #8492a6;
                                  font-size: 13px;
                                "
                                >￥ {{ apply.amount }} 元</span
                              >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="预算合计" prop="detailsAmount">
                          <el-input
                            v-model="details.detailsAmount"
                            placeholder="请输入预算合计"
                            type="number"
                            disabled
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="费用描述" prop="detailsDesc">
                          <el-input
                            v-model="details.detailsDesc"
                            placeholder="请输入费用详情描述"
                            disabled
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                          <el-input
                            v-model="details.remark"
                            placeholder="请输入备注"
                            disabled
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-card>
                 
                </div>
                 <el-divider></el-divider>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="费用总计" prop="aggregationCharge">
                  <el-input
                    readonly
                    v-model="form.aggregationCharge"
                    placeholder="请输入费用总计"
                  >
                    <template slot="append">{{
                      digitUppercase(form.aggregationCharge)
                    }}</template></el-input
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="管理层意见" prop="opinion">
                  <el-input
                    v-model="form.opinion"
                    placeholder="请输入管理层意见"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="附件" prop="url">
                  <file-upload v-model="form.url" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-divider>审批通道</el-divider>
                <el-form-item label="电子签名" prop="signature">
                  <div class="box">
                    <VueSignaturePad
                      width="100%"
                      height="250px"
                      ref="signaturePad"
                    />
                    <el-button @click="undo" type="text" class="box-button"
                      >清空签名</el-button
                    >
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="审批意见" prop="message">
                  <el-input
                    v-model="form.message"
                    type="textarea"
                    placeholder="请输入审批意见"
                    :autosize="{ minRows: 4, maxRows: 4 }"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row  v-if="!disabled">
              <el-col :span="24">
                <el-form-item>
                  <el-button type="primary" @click="handleBtn('PASS')"
                    >通过</el-button
                  >
                  <el-button @click="handleBtn('REJECT')">驳回</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-row>
      </el-card>
    </el-drawer>
  </div>
</template>

<script>
import { getCrmOrderAllNoPage } from "@/api/crm/order";
import { getCrmCustomerAllNoPage } from "@/api/crm/customer";
import {
  selectCrmFeeApplyByOrderIdAndCreateBy
} from "@/api/crm/apply";

import {
  getClear, audit
} from "@/api/crm/clear";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { deptTreeSelect, getUserListByStatus } from "@/api/system/user";
export default {
  name: "Approve",
  dicts: ["is_required"],
  components: { Treeselect },
  props: {
    /* 业务id */
    value: {
      type: String,
      default: "",
    },

    /* 实例id */
    taskId: {
      type: String,
      default: "",
    },

    /* 是否可以标编辑 */
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      deptOptions: [],
      itemWidth: 12,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 指定跳转节点
      nodeCode: "",
      customerList: [],
      // 商机项目立项表格数据
      orderRegisterList: [],
      userList: [],
      applyList: [],
      rules: {
        // signature: [
        //   {
        //     required: true,
        //     validator: this.validateDetails,
        //     trigger: "change",
        //   },
        // ],
      },
    };
  },
  created() {
    this.reset();
    this.getCrmCustomerAllNoPage();
    this.getCrmOrderAllNoPage();
    this.getDeptTree();
    this.getClear()
    this.getUserListByStatus()
  },
  mounted(){
    setTimeout(() => {
      let data = window.localStorage.getItem("签名_" + this.$store.getters.userId)
      if(data){
        this.$refs.signaturePad.fromDataURL(data);
      }
    }, 500)
  },
  methods: {
    
    selectCrmFeeApplyByOrderIdAndCreateBy(){
      console.log(this.form.orderId)
      selectCrmFeeApplyByOrderIdAndCreateBy(this.form.orderId).then(res => {
        this.applyList = res.data
      })
    },
    getCrmOrderAllNoPage() {
      getCrmOrderAllNoPage({}).then((res) => {
        this.orderList = res.data;
      });
    },
    getUserListByStatus() {
      getUserListByStatus({ status: "0" }).then((res) => {
        this.userList = res.data;
      });
    },
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    validateDetails(rule, value, callback) {
      const { isEmpty, data } = this.$refs.signaturePad.saveSignature();
      if (isEmpty) {
        callback(new Error("电子签名必须填写"));
      } else {
        callback();
      }
    },
    // 撤销操作
    undo() {
      this.$refs.signaturePad.clearSignature();
    },
    getCrmCustomerAllNoPage() {
      getCrmCustomerAllNoPage({}).then((res) => {
        this.customerList = res.data;
      });
    },
    async getClear() {
      await getClear(this.value).then((response) => {
        if (!response.data) {
          this.$modal.alertWarning("代办任务不存在");
        }     
        this.form = response.data;
        this.selectCrmFeeApplyByOrderIdAndCreateBy()
        this.form.principalId = this.form.principalId ? this.form.principalId.split(",") : null;
        this.form.detailsList.forEach(element => {
          this.detailsTypeChange(element)
          this.$forceUpdate()
        });
        this.title = this.form.createBy + " 项目结算";
        this.open = true;
      });
    },
    detailsTypeChange(details) {
      details.itemWidth = details.detailsType === "1" || details.detailsType === "4" ? 8 : 12;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        message: null,
        id: null,
        type: null,
        reason: null,
        startTime: null,
        endTime: null,
        day: null,
        instanceId: null,
        nodeCode: null,
        nodeName: null,
        flowStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 审核通过按钮 */
    handleBtn(skipType) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.taskId = this.taskId;
          this.form.skipType = skipType;
          const { isEmpty, data } = this.$refs.signaturePad.saveSignature();
          this.form.signature = data;
          this.form.principalId = null
          audit(this.form).then((response) => {
            this.$modal.msgSuccess("办理成功");
            window.localStorage.setItem("签名_" + this.$store.getters.userId, this.form.signature)
            this.open = false;
            this.$emit("refresh");
          });
        }
      });
    },
  },
};
</script>

<style scoped>
::v-deep .el-drawer__header {
  margin-bottom: 20px;
}
::v-deep .el-input.is-disabled .el-input__inner {
  background-color: white;
  border-color: #dfe4ed;
  color: black;
  cursor: not-allowed;
}

::v-deep .el-textarea.is-disabled .el-textarea__inner {
  background-color: white;
  border-color: #dfe4ed;
  color: black;
  cursor: not-allowed;
}

::v-deep .details .el-table--medium .el-table__cell {
  padding: 0;
}

::v-deep .details .el-input--medium {
  margin: 10px 10px 10px -10px;
}

.box {
  width: 100%;
  height: 250px;
  border: 1px solid #dcdfe6;
  position: relative;
}

.box-button {
  position: absolute;
  top: 215px;
  left: 93%;
}

.box-card {
  margin: 20px;

}
.box-form {
  overflow: auto;
  max-height: 600px;
  background-color: #f5f7fa;
}
</style>